class ArtworksController < ApplicationController
  before_filter :require_admin,           :only => [:new,   :create,  :edit,    :update,  :destroy]
  before_filter :find_artwork,            :only => [:show,  :edit,    :update,  :destroy]
  before_filter :find_list_items,         :only => [:show,  :new,     :create,  :edit]  

  def index
    @artworks = Artwork.find(:all, :conditions => ['thumbnail IS ?', nil], :order => 'created_at DESC')
  end

  def show
    @comment = Comment.new
  end

  def new
    @artwork = Artwork.new
  end

  def create
    @artwork = Artwork.new(params[:artwork])
    @artwork.save!
    flash[:update] = 'The artwork has been added'
    redirect_to artwork_url(@artwork)
  rescue ActiveRecord::RecordInvalid
    flash[:error] = "Oops, that didn't work, see below."
    render :action => 'new'
  end

  def edit
  end

  def update
    @artwork.update_attributes!(params[:artwork])
    flash[:update] = 'The artwork information has been updated.'
    redirect_to artwork_url(@artwork)
  rescue ActiveRecord::RecordInvalid
    flash[:error] = "Oops, that didn't work, see below."
    render :action => 'edit'
  end

  def destroy
    @artwork.destroy
    flash[:update] = 'The artwork has been deleted.'
    redirect_to artworks_url
  end

protected
  def require_login
    unless logged_in?
      flash[:error] = 'You must be logged in to do that'
      redirect_to login_url
    end
  end
  def require_admin
    if logged_in?
      unless current_user.is_admin?
        flash[:error] = "Must be an administrator to do that, sorry."
        redirect_back_or_default('/')
      end
    else
      flash[:error] = 'You must be logged in to do that'
      redirect_to login_url
    end
  end
  def find_artwork
    @artwork = Artwork.find params[:id]
  end
  def find_list_items
    @songs    = Song.find     :all, :order => 'created_at desc'
    @shows    = Show.find     :all, :order => 'created_at desc'
    @albums   = Album.find    :all, :order => 'created_at desc'
    @videos   = Video.find    :all, :order => 'created_at desc'
    @photos   = Photo.find    :all, :order => 'created_at desc', :conditions => ['thumbnail IS ?', nil]
    @users    = User.find     :all, :order => 'created_at desc'
  end
end
